package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.cwgl.VoucherDao;
import com.hnkywl.sts.dao.cwgl.VoucherType;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.*;

import com.hnkywl.sts.webservice.bg.util.StackTraceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 说明：
 * 包:        com.hnkywl.jip.service
 * 类描述:    [一句话描述该类的功能]
 * 创建人:    ZHUCHG
 * 创建时间: 13-2-22 下午2:36
 * 修改人:    ZHUCHG
 * 修改时间: 13-2-22 下午2:36
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Service
public class VoucherService {
    private InterfaceParam interfaceParam;
    private VoucherDao voucherDao;
    //    private VoucherGenerateSvrStub voucherGenerateSvr;
//    private VoucherRevokeSvrStub voucherRevokeSvr;
//    private VoucherSyncSvrStub voucherSyncSvr;
    private WebserviceLogService webserviceLogService;

    public void checkJiuqiUsernamePassword() {
        if (StringUtils.isEmpty(YgService.getCurrentYgJiuqiUsername())) {
            throw new RuntimeException("您没有财务系统用户名，不具有导入权限!");
        }
        if (StringUtils.isEmpty(YgService.getCurrentYgJiuqiPassword())) {
            throw new RuntimeException("您没有财务系统密码，不具有导入权限!");
        }
        String xm = YgService.getCurrentYgName();
        if (StringUtils.isEmpty(xm)) {
            throw new RuntimeException("该登陆用户没有填写用户姓名，请联系管理员添加姓名!");
        }
//        String xmpy = Pinyin.getPinYin(xm);
//        if (!xmpy.equals(YgService.getCurrentYgJiuqiUsername().trim())) {
//            throw new RuntimeException("该用户的久其用户名与其登陆用户不匹配，请重新设置!");
//        }
    }

    /**
     * 生成凭证
     *
     * @param data
     * @return
     */
    public String generateVoucher(Map<String, Object> data) {
        String xml = null;
        String result = null;
        String exception = null;
        Date startDate = null;
        Date endDate = null;

        try {
            xml = Freemarker2Xml.generateU8VoucherXml(data);
// ---------------------------久其接口---------------------------------
//            VoucherGenerateSvrStub.GenerateVoucher gv = new VoucherGenerateSvrStub.GenerateVoucher();
//            gv.setXml(xml);
//            voucherGenerateSvr._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);//5分钟
//            startDate = new Date();
//            VoucherGenerateSvrStub.GenerateVoucherResponse gvr = voucherGenerateSvr.generateVoucher(gv);
//            endDate = new Date();
//            result = gvr.get_return();
// -------------------------------END---------------------------------

// ---------------------------U8接口---------------------------------
//            Service1Stub.ImportVoucher iv = new Service1Stub.ImportVoucher();
//            iv.setXml(xml);
//            service1Stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);//5分钟
//            startDate = new Date();
//            Service1Stub.ImportVoucherResponse ivr = service1Stub.importVoucher(iv);
//            endDate = new Date();
//            result = ivr.getImportVoucherResult();
// -------------------------------END---------------------------------
        } catch (Exception e) {
            endDate = new Date();
            e.printStackTrace();
            exception = StackTraceUtil.getStackTrace(e);
        }
        webserviceLogService.saveClientLog(
                VoucherService.class.getName(),
                "generateVoucher",
                xml,
                result + " 执行时间：" + (endDate.getTime() - startDate.getTime()) / 1000 + "秒",
                exception,
                ""
        );
        return result;
    }

    /**
     * 撤销凭证
     *
     * @param data
     * @return
     */
    public String revokeVoucher(Map data) {
        String xml = null;
        String result = null;
        String exception = null;
        try {
// ---------------------------久其接口---------------------------------
//            xml = Freemarker2Xml.revokeVoucherXml(data);
//            VoucherRevokeSvrStub.RevokeVoucher rv = new VoucherRevokeSvrStub.RevokeVoucher();
//            rv.setXml(xml);
//            VoucherRevokeSvrStub.RevokeVoucherResponse rvr = voucherRevokeSvr.revokeVoucher(rv);
//            result = rvr.get_return();
// -------------------------------END---------------------------------

// ---------------------------U8接口---------------------------------
//            xml = Freemarker2Xml.revokeU8VoucherXml(data);
//            Service1Stub.DeleteVoucher dv = new Service1Stub.DeleteVoucher();
//            dv.setXml(xml);
//            service1Stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);//5分钟
//            Service1Stub.DeleteVoucherResponse dvr = service1Stub.deleteVoucher(dv);
//            result = dvr.getDeleteVoucherResult();
// -------------------------------END---------------------------------
        } catch (Exception e) {
            e.printStackTrace();
            exception = StackTraceUtil.getStackTrace(e);
        }
        webserviceLogService.saveClientLog(
                VoucherService.class.getName(),
                "revokeVoucher",
                xml,
                result,
                exception,
                ""
        );
        return result;
    }

    /**
     * 同步凭证
     *
     * @param data
     * @return
     */
    public String syncVoucher(Map data) {
        String xml = null;
        String result = null;
        String exception = null;
        try {
            // ---------------------------久其接口---------------------------------
            //xml = Freemarker2Xml.syncVoucherXml(data);
            //VoucherSyncSvrStub.SyncVoucher sv = new VoucherSyncSvrStub.SyncVoucher();
            // sv.setXml(xml);
            //VoucherSyncSvrStub.SyncVoucherResponse svr = voucherSyncSvr.syncVoucher(sv);
            // result = svr.get_return();
            // -------------------------------END---------------------------------

            // ---------------------------U8接口---------------------------------
//            xml = Freemarker2Xml.syncU8VoucherXml(data);
//            Service1Stub.QueryVoucherNo qvn = new Service1Stub.QueryVoucherNo();
//            qvn.setXml(xml);
//            service1Stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);//5分钟
//            Service1Stub.QueryVoucherNoResponse qvnr = service1Stub.queryVoucherNo(qvn);
//            result = qvnr.getQueryVoucherNoResult();
            // -------------------------------END---------------------------------
        } catch (Exception e) {
            e.printStackTrace();
            exception = StackTraceUtil.getStackTrace(e);
        }
        webserviceLogService.saveClientLog(
                VoucherService.class.getName(),
                "syncVoucher",
                xml,
                result,
                exception,
                ""
        );
        return result;
    }

    /**
     * 获取凭证头
     *
     * @return
     */
    public Map getMsgHeader() {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String systemDate = simple.format(new Date());
        Map<String, Object> msgheader = new HashMap<String, Object>();
        msgheader.put("sourcesystemid", interfaceParam.getSourceSystemId()); //系统标识
        msgheader.put("sourcesystemname", interfaceParam.getSourceSystemName());//系统名称
        msgheader.put("userid", YgService.getCurrentYg().getId());//久其用户ID
        msgheader.put("username", YgService.getCurrentYgJiuqiUsername());//久其用户名称
        //MD5 32位小写
        msgheader.put("password", Md5.md5Encrypt(YgService.getCurrentYgJiuqiPassword()));//用户密码
        msgheader.put("submitdate", systemDate);//调用时间
        return msgheader;
    }

    /**
     * 开始导入凭证
     *
     * @param id
     * @param type
     * @return
     */
    @Transactional
    public Boolean beginGenerateVoucher(Long id, VoucherType type) {
        return voucherDao.beginGenerateVoucher(id, type);
    }

    /**
     * 生成凭证成功
     *
     * @param uuid
     * @param voucherId
     * @param voucherNum
     * @param year
     * @param id
     * @param type
     * @return
     */
    @Transactional
    public Boolean generateVoucherSuccess(String uuid, String voucherId, String voucherNum, Integer year, Long id, VoucherType type) {
        return voucherDao.generateVoucherSuccess(uuid, voucherId, voucherNum, year, id, type);
    }

    /**
     * 开始撤销凭证
     *
     * @param id
     * @param type
     * @return
     */
    @Transactional
    public Boolean beginRevokeVoucher(Long id, VoucherType type) {
        return voucherDao.beginRevokeVoucher(id, type);
    }

    /**
     * 撤销凭证成功
     *
     * @param id
     * @param type
     * @return
     */
    @Transactional
    public Boolean revokeVoucherSuccess(Long id, VoucherType type) {
        return voucherDao.revokeVoucherSuccess(id, type);
    }

    /**
     * 重置凭证
     *
     * @param id
     * @param voucherType
     * @return
     */
    @Transactional
    public String restVoucher(Long id, VoucherType voucherType) {
        Map<String, String> result = new HashMap<String, String>();
        String flag = "0";
        String message = "";
        try {
            Boolean success = voucherDao.restVoucher(id, voucherType);
            if (success) {
                flag = "1";
                message = "重置成功!";
            } else {
                flag = "0";
                message = "重置失败!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = "0";
            message = e.getMessage();
        }
        result.put(XmlParse.RESPONSEFLAG, flag);
        result.put(XmlParse.RESPONSEMESSAGE, message);
        Gson gson = new Gson();
        return gson.toJson(result);
    }


    /**
     * 同步凭证
     *
     * @param id
     * @param voucherType
     * @return
     */
    @Transactional
    public String syncVoucher(Long id, Integer voucherNum, VoucherType voucherType) {
        Map<String, String> result = new HashMap<String, String>();
        String flag = "0";
        String message = "";
        try {
            voucherDao.syncVoucher(id, voucherNum, voucherType);
            flag = "1";
            message = "重置成功!";
        } catch (Exception e) {
            e.printStackTrace();
            flag = "0";
            message = e.getMessage();
        }
        result.put(XmlParse.RESPONSEFLAG, flag);
        result.put(XmlParse.RESPONSEMESSAGE, message);
        Gson gson = new Gson();
        return gson.toJson(result);
    }

    @Autowired
    public void setInterfaceParam(InterfaceParam interfaceParam) {
        this.interfaceParam = interfaceParam;
    }

    @Autowired
    public void setVoucherDao(VoucherDao voucherDao) {
        this.voucherDao = voucherDao;
    }

//    @Autowired
//    public void setVoucherGenerateSvr(@Qualifier("voucherGenerateSvr") VoucherGenerateSvrStub voucherGenerateSvr) {
//        this.voucherGenerateSvr = voucherGenerateSvr;
//    }
//
//    @Autowired
//    public void setVoucherRevokeSvr(@Qualifier("voucherRevokeSvr") VoucherRevokeSvrStub voucherRevokeSvr) {
//        this.voucherRevokeSvr = voucherRevokeSvr;
//    }
//
//    @Autowired
//    public void setVoucherSyncSvr(@Qualifier("voucherSyncSvr") VoucherSyncSvrStub voucherSyncSvr) {
//        this.voucherSyncSvr = voucherSyncSvr;
//    }

    @Autowired
    public void setWebserviceLogService(WebserviceLogService webserviceLogService) {
        this.webserviceLogService = webserviceLogService;
    }
}
